package com.histone.heartbeat.web;

import com.histone.heartbeat.pojo.WxProperties;
import com.histone.heartbeat.service.MsgService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@RestController
@Slf4j
public class WxController {
    @Autowired
    private WxProperties wxProperties;

    @Autowired
    private MsgService msgService;


    /**
     * 接收微信服务器验证
     */
    @GetMapping("wx")
    public String verify(String signature, String timestamp, String nonce,String echostr){
        log.info(signature, timestamp, nonce, echostr);
        String[] array = {wxProperties.getToken(),timestamp,nonce};
        Arrays.sort(array);
        String result = array[0]+array[1]+array[2];
        String digest = DigestUtils.sha1Hex(result.getBytes()).toLowerCase();
        if(digest.equals(signature)){
            // 可不经过以上验证直接返回 但不建议
            return echostr;
        } else {
            return null;
        }
    }

    @PostMapping("wx")
    public String message(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 微信服务器POST消息时用的是UTF-8编码，在接收时也要用同样的编码，否则中文会乱码；
        request.setCharacterEncoding("UTF-8");
        // 在响应消息（回复消息给用户）时，也将编码方式设置为UTF-8，原理同上；
        response.setCharacterEncoding("UTF-8");
        String respXml = msgService.receiveMsg(request);
//        response.getWriter().write(respXml);
        return respXml;

    }


}
